// ==UserScript==
// @name         自动答题+检测学习进度+检测关闭
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  try to take over the world!
// @author       You
// @match        https://www.zhifa315.com/learn/*
// @icon         https://www.zhifa315.com/favicon.ico
// @updateURL    https://gitee.com/clearlove123/video/raw/master/learn.user.js
// @installURL   https://gitee.com/clearlove123/video/raw/master/learn.user.js
// @downloadURL  https://gitee.com/clearlove123/video/raw/master/learn.user.js
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==


(function () {
    var href = window.location.href;

    // 隔多少s刷新一次
    var cycleTime = 30 * 1000;

    // 提交次数
    var num = 0;

    // 设置log
    function setLog(stuNum, total) {
        var log = [
            "title:" + getTitle(),
            "progress:" + stuNum + "/" + total,
            "time:" + getTime(new Date())
        ];
        localStorage.setItem("log", log);
    }

    // 拿标题
    function getTitle() {
        var div = document.getElementsByClassName("docTitle")[0];
        return div.innerText;
    }

    // 睡眠
    function sleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }

    // 获取当前时间
    function getTime(t) {
        var h = t.getHours();
        var m = t.getMinutes();
        var s = t.getSeconds();
        return "时间：" + h + "点" + m + "分" + s + "秒";
    }

    // 获取学习进度数组
    function getText(ul) {
        let i;
        var text = [];
        // 看看正在播放的是那个
        for (i = 0; i < ul.length; i++) {
            // 把每个视频名字提取出来
            text[i] = ul[i].innerText.substr(-5).replace("]", "").replace("[", "");
        }
        return text;
    }

    // 检查学习进度
    async function check(stuNum, ul) {
        // 点下一个
        if (await stuNum === (ul.length - 1)) {
            await ul[0].click();
        } else {
            await ul[stuNum + 1].click();
        }
        await sleep(1000);
        // 获取进度
        ul = await document.getElementsByTagName("li")
        var text = getText(ul);
        if (await text[stuNum] === "学习中") {
            //点回正在学的那个
            await ul[stuNum].click();
        }
    }

    // 30s自动答题
    async function main() {
        var ant = document.getElementsByClassName("ant-modal-content")[0];
        if (typeof (ant) != "undefined") {
            // 点选项
            document.getElementsByClassName("questionBody")[0].getElementsByTagName("div")[1].getElementsByTagName("label")[0].click();
            await sleep(100);
            // 点提交
            document.getElementsByClassName("ant-btn ant-btn-primary")[0].click();
            console.log("第" + num++ + "提交成功！.." + getTime(new Date()));
        }
    }

    // 35min检测学习进度
    async function test() {
        console.log("正在运行检测学习进度...");
        var time = 0;
        var i;
        await sleep(10 * 1000);
        while (true) {
            time = Math.floor(Math.random() * 5 * 60 * 1000) + 35 * 60 * 1000;
            console.log(getTime(new Date()) + "检测学习进度结束...延时=" + (time / 1000 / 60) + "分钟");
            await sleep(time);
            var ul = await document.getElementsByTagName("li");
            if (ul.length === 1) {
                await sleep(time);
                setLog("就一个", "");
                window.location.reload();
            }
            // 获取进度数组
            var text = getText(ul);
            // 循环进度数组
            for (i = 0; i < text.length; i++) {
                if (await text[i] === "学习中") {
                    // 得到进度
                    setLog(i, text.length);
                    await ul[i].click();
                    break;
                } else if (text[i] === "正在学习") {
                    // 得到进度
                    setLog(i, text.length);
                    await check(i, ul);
                    break;
                }
            }

        }
    }

    // 30s检测关闭
    async function closeWindows() {
        if (localStorage.getItem("flag") === "true") {
            console.log("准备关闭");
            localStorage.setItem("flag", false);
            await sleep(10);
            window.close();
        }
    }

    // 两分半钟提交一次update
    async function beat(i) {
        await fetch("https://www.zhifa315.com/index.php/site/study/update_time_new", {
            "headers": {
                "accept": "application/json, text/plain, *!/!*",
                "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
                "content-type": "application/x-www-form-urlencoded",
                //"sec-ch-ua": "\"Chromium\";v=\"94\", \"Microsoft Edge\";v=\"94\", \";Not A Brand\";v=\"99\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin"
            },
            "referrer": href,
            "referrerPolicy": "strict-origin-when-cross-origin",
            "body": "",
            "method": "POST",
            "mode": "cors",
            "credentials": "include"
        });
        if (i === 1) {
            console.log("------------");
            console.log("心跳信号发送成功..." + getTime(new Date()));
            console.log("------------");
        }
    }

    async function run() {
        var i = 30;
        // 35min检测学习进度
        test();
        while (true) {
            if (i === 30) {
                console.log("------------");
                console.log("正在运行自动答题...");
                console.log("正在运行视频播放检测关闭...");
                console.log("现在是：" + getTime(new Date()));
                console.log("------------");
                i = 0;
            }
            if (i % 2 === 1) {
                // 发送心跳信号
                await beat(i);
                await sleep(100);
            }
            // 30s自动答题
            await main();
            await sleep(100);
            await closeWindows();
            await sleep(100);
            i++;
            await sleep(cycleTime);
        }

    }

    run();

})();